const SocketIO = require('socket.io');
const { redisGet, redisSet } = require('../utils/redis');
const redisUtils = require('../utils/redisUtils');
const { timer } = require('../utils/func');
const { updateService } = require('../model/user')


// 创建一个全局单例
const socketWrapper = {
    io: null,

    initialize(httpServer) {
        if (this.io) {
            console.info('Socket.IO 已经初始化过了');
            return;
        }

        this.io = new SocketIO.Server(httpServer, {
            cors: {
                origin: '*',
                methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            },
            pingTimeout: 60000, // 60秒超时
        });

        // 连接处理
        this.on('connection', async (socket) => {
            const query = socket.handshake.query;
            console.log('新客户端连接:', query);
            if (query.imKey) {
                socket.imKey = query.imKey;
                const userInfo = await redisGet(`mim-${query.imKey}`);
                if (userInfo) {
                    userInfo.socketId = socket.id;
                    userInfo.online = 1;
                    await redisSet(`mim-${query.imKey}`, userInfo);
                }
                // 加入全局推送房间
                socket.join(`mim-global-push-room`);
                // 更新在线状态
                try {
                    await updateService(query.imKey, { imKey: query.imKey, online: 1 });
                } catch (e) {
                    console.log('updateService error', e);
                }
            }
            setTimeout(() => {
                socket.emit('connection', {
                    imKey: query.imKey
                });
            }, 500);
            socket.on('disconnect', async () => {
                if (query.imKey) {
                    const userInfo = await redisGet(`mim-${query.imKey}`);
                    if (userInfo) {
                        userInfo.online = 0;
                        await redisSet(`mim-${query.imKey}`, userInfo);
                    }
                    // 更新在线状态
                    try {
                        await updateService(query.imKey, { imKey: query.imKey, online: 0 });
                    } catch (e) {
                        console.log('updateService error', e);
                    }
                }
            });
            socket.conn.on('packetCreate', async (packet) => {
                if (packet.type === 'ping') {
                    // 更新用户的最后在线时间
                    const userInfo = await redisGet(`mim-${query.imKey}`);
                    if (userInfo) {
                        userInfo.socketId = socket.id;
                        userInfo.online = 1;
                        userInfo.lastOnlineTime = new Date().getTime();
                        await redisSet(`mim-${query.imKey}`, userInfo);
                    }
                }
            });
        });
    },

    emit(event, data) {
        if (!this.io) {
            console.error('Socket.IO 还未初始化');
            return;
        }
        this.io.emit(event, data);
    },

    on(event, callback) {
        if (!this.io) {
            console.error('Socket.IO 还未初始化');
            return;
        }
        this.io.on(event, callback);
    },
    // 获取 io 实例
    getIO() {
        if (!this.io) {
            throw new Error('Socket.IO 还未初始化');
        }
        return this.io;
    }
};

// 使用 module.exports 导出
module.exports = socketWrapper; 